<?php ;

Themes::$data = include mnmpath.'templates/data.inc';

class Themes {
    public static $data;
    public static $cookieName = 'theme';
    public static $paramName = 'theme';

    //----------------

    public static function get() {
        $theme = self::aget($_GET, self::$paramName);
        if ($theme && self::valid($theme)) return $theme;

        $theme = self::aget($_COOKIE, self::$cookieName);
        if ($theme && self::valid($theme)) return $theme;
        if ($theme) self::clearCookie();

        return self::$data['default'];
    }

    public static function valid($theme) {
        try {
            self::validate($theme);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public static function validate($theme) {
        if (! preg_match('{^[-\w]+$}', $theme)) {
            throw new Exception("invalid theme " . $theme);
        }

        if (! isset(self::$data['themes'][$theme])) {
            throw new Exception("unknown theme " . $theme);
        }

        $canary = mnmpath."templates/{$theme}/pligg.tpl";
        if (! file_exists($canary)) {
            throw new Exception("nonexistent theme " . $theme);
        }
    }

    public static function clearCookie() {
        setcookie(self::$cookieName, '', 1, '/');
    }

    public static function setCookie($theme) {
        if (self::valid($theme)) {
            setcookie(self::$cookieName, $theme, pow(2, 32) - 1, '/');
            return true;
        }
        return false;
    }

    //----------------

    private static function aget($array, $key, $default=null) {
        return isset($array[$key]) ? $array[$key] : $default;
    }
}
